package com.example.musicwebcon.exception;

import com.example.musicwebcon.model.ResponseMessage;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice    //统一处理
public class GlobalExceptionHandlerAdvice {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandlerAdvice.class);
    /**
     * 处理 IllegalArgumentException 异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<ResponseMessage> handleIllegalArgumentException(IllegalArgumentException ex,
                                                                          HttpServletRequest request,
                                                                          HttpServletResponse response) {
        // 记录日志信息
        logger.error("请求路径：{}，异常信息：{}", request.getRequestURI(), ex.getMessage());
        // 返回友好的错误响应
        return ResponseEntity.badRequest().body(ResponseMessage.error(ex.getMessage()));
    }

    /**
     * 处理所有 Exception 异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ResponseMessage> handleException(Exception ex,
                                                           HttpServletRequest request,
                                                           HttpServletResponse response) {
        // 打印堆栈信息便于调试
        logger.error("请求路径：{}，服务器内部异常：", request.getRequestURI(), ex);
        // 返回通用的服务器错误信息
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(ResponseMessage.error("服务器内部错误，请稍后重试"+ex.getMessage()));
    }
}
